<?php

class Admin_Model_DbTable_Resource extends Zend_Db_Table_Abstract
{
    protected $_name = 'resource';
    protected $_id = 'resID';

    public function getAll($where, $options) {
        $sql = $this->getAdapter()->select()
                ->from($this->_name)
                ->order("create_on DESC");
        
        if (is_array($where)) {
            foreach($where as $key=>$value) {
                $sql->where($key, $value);
            }
        }
        
        if (is_array($options)) {
            if (isset($options['limit']))
                foreach ($options['limit'] as $key => $value) {
                    $sql->limit($key, $value);
                }
        }
        
        return $this->_db->fetchAll($sql);
    }
    
    public function getRow($id) {
        $sql = $this->getAdapter()->select()
                ->from(array('a'=>$this->_name))
                ->joinLeft(array('b'=>'resource_meta'), 'b.resID = a.resID', 
                        array('api_version', 'http_method', 'response_fmt', 'family', 'auth'))
                ->where("a.$this->_id = ?", $id);
        
        return $this->_db->fetchRow($sql);
    }
    
    public function countRows($where) {
        $sql = $this->getAdapter()->select()
                ->from($this->_name, 'COUNT(resID)');                
        
        if (is_array($where)) {
            foreach($where as $key=>$value) {
                $sql->where($key, $value);
            }
        }
            
        return $this->getAdapter()->fetchOne($sql);
    }
    
    public function checkMeta($where) {
        $sql = $this->getAdapter()->select()
                ->from('resource_meta', 'COUNT(resID)');                
        
        if (is_array($where)) {
            foreach($where as $key=>$value) {
                $sql->where($key, $value);
            }
        }
            
        return $this->getAdapter()->fetchOne($sql);
    }
    
    public function doSave($data = array()) {
        return $this->getAdapter()->insert($this->_name, $data);
    }
    
    public function doUpdate($data = array(), $where = '') {
        return $this->getAdapter()->update($this->_name, $data, array("$this->_id = ?"=>$where));
    }
    
    public function doDelete($where) {
        return $this->getAdapter()->delete($this->_name, array("$this->_id = ?" => $where));
    }
    
    public function getCategory() {
        $sql = $this->getAdapter()->select()
                ->from('category', array('catID', 'name'));
        
        return $this->_db->fetchAll($sql);
    }
    
    public function saveMeta($data = array()) {
        return $this->getAdapter()->insert('resource_meta', $data);
    }
    
    public function updateMeta($data = array(), $id = '') {
        return $this->getAdapter()->update('resource_meta', $data, array("resID = ?"=>$id));
    }
}